import React, { useState } from 'react';
import apiClient from '../../utils/apiClient';
    import './index.css';

    const UploadDocumentPage = ({ kbId, kbName }) => {
      const [files, setFiles] = useState([]);
      const [uploadProgress, setUploadProgress] = useState({}); // { [fileId]: { status, progress } }
      const [enableQAExtraction, setEnableQAExtraction] = useState(true);
      const [enableIndexEnhancement, setEnableIndexEnhancement] = useState(true);

      const handleFileChange = (event) => {
        const selectedFiles = Array.from(event.target.files);
        setFiles(prevFiles => [...prevFiles, ...selectedFiles.map(file => ({
          file,
          id: `${file.name}-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`, // More unique ID
          status: 'pending', 
          progress: 0
        }))]);
        // Clear the input value to allow selecting the same file again
        event.target.value = null; 
      };

      const handleUpload = async () => {
        const filesToUpload = files.filter(f => !uploadProgress[f.id] || uploadProgress[f.id]?.status === 'pending' || uploadProgress[f.id]?.status === 'error');
        
        if (filesToUpload.length === 0) {
            alert("请先选择新文件或所有已选文件已成功上传或正在上传。");
            return;
        }

        for (const fileObj of filesToUpload) {
          try {
            const formData = new FormData();
            formData.append('file', fileObj.file);

            setUploadProgress(prev => ({ 
              ...prev, 
              [fileObj.id]: { status: 'uploading', progress: 0 } 
            }));

            await apiClient.uploadFile(`/kb/${kbId}/upload`, formData, (progress) => {
              setUploadProgress(prev => ({
                ...prev,
                [fileObj.id]: { 
                  status: progress === 100 ? 'success' : 'uploading',
                  progress
                }
              }));
            });

            // 添加额外的文档处理选项
            await apiClient.post(`/kb/${kbId}/document/${fileObj.id}/process`, {
              qaExtraction: enableQAExtraction,
              indexEnhancement: enableIndexEnhancement
            });
          } catch (error) {
            console.error(`Error uploading ${fileObj.file.name}:`, error.message);
          }
        }
      };
      
      const getStatusIcon = (status) => {
        switch (status) {
          case 'uploading': return <i className="fas fa-spinner fa-spin status-icon uploading"></i>;
          case 'success': return <i className="fas fa-check-circle status-icon success"></i>;
          case 'error': return <i className="fas fa-times-circle status-icon error"></i>;
          default: return <i className="fas fa-hourglass-start status-icon pending"></i>;
        }
      };

      const removeFile = (fileId) => {
        setFiles(prevFiles => prevFiles.filter(f => f.id !== fileId));
        setUploadProgress(prevProgress => {
          const newProgress = {...prevProgress};
          delete newProgress[fileId];
          return newProgress;
        });
      };

      return (
        <div className="container upload-page">
          <div className="page-header">
            <h1><i className="fas fa-cloud-upload-alt"></i> 上传文档到 "{kbName || 'AI 知识库'}"</h1>
            <button onClick={() => window.location.hash = `#/kb/${kbId}?name=${encodeURIComponent(kbName)}`} className="secondary">
              <i className="fas fa-arrow-left"></i> 返回知识库
            </button>
          </div>

          <div className="upload-settings-area">
            <div className="upload-area">
              <input type="file" id="file-upload" multiple onChange={handleFileChange} style={{ display: 'none' }} />
              <label htmlFor="file-upload" className="upload-dropzone">
                <i className="fas fa-file-medical fa-3x"></i>
                <p>拖拽文件到此处，或点击选择文件</p>
                <span>支持 PDF, DOCX, TXT, MD 等格式</span>
              </label>
            </div>

            <div className="upload-options">
              <div className="option-item">
                <input
                  type="checkbox"
                  id="qa-extraction"
                  checked={enableQAExtraction}
                  onChange={(e) => setEnableQAExtraction(e.target.checked)}
                />
                <label htmlFor="qa-extraction"><i className="fas fa-question-circle"></i> 开启QA提取</label>
              </div>
              <div className="option-item">
                <input
                  type="checkbox"
                  id="index-enhancement"
                  checked={enableIndexEnhancement}
                  onChange={(e) => setEnableIndexEnhancement(e.target.checked)}
                />
                <label htmlFor="index-enhancement"><i className="fas fa-search-plus"></i> 开启索引增强</label>
              </div>
            </div>
          </div>


          {files.length > 0 && (
            <div className="file-list-section">
              <h3>待上传文件 ({files.length}):</h3>
              <ul className="file-list">
                {files.map((fileObj) => (
                  <li key={fileObj.id} className={`file-item status-${uploadProgress[fileObj.id]?.status || 'pending'}`}>
                    <span className="file-name"><i className="fas fa-file-alt"></i> {fileObj.file.name}</span>
                    <span className="file-size">({(fileObj.file.size / 1024).toFixed(2)} KB)</span>
                    <div className="progress-bar-container">
                      { (uploadProgress[fileObj.id]?.status === 'uploading' || uploadProgress[fileObj.id]?.status === 'success' || uploadProgress[fileObj.id]?.status === 'error') &&
                        <div 
                            className="progress-bar" 
                            style={{ width: `${uploadProgress[fileObj.id]?.progress || 0}%` }}
                        ></div>
                      }
                    </div>
                    <span className="file-status">
                      {getStatusIcon(uploadProgress[fileObj.id]?.status)}
                      {uploadProgress[fileObj.id]?.status === 'uploading' && `${uploadProgress[fileObj.id]?.progress}%`}
                    </span>
                    <button 
                      onClick={() => removeFile(fileObj.id)} 
                      className="remove-file-btn"
                      title="移除文件"
                    >
                      <i className="fas fa-times"></i>
                    </button>
                  </li>
                ))}
              </ul>
              <button 
                onClick={handleUpload} 
                className="upload-btn" 
                disabled={files.filter(f => !uploadProgress[f.id] || uploadProgress[f.id]?.status === 'pending' || uploadProgress[f.id]?.status === 'error').length === 0}
              >
                <i className="fas fa-rocket"></i> 开始上传
              </button>
            </div>
          )}
        </div>
      );
    };

    export default UploadDocumentPage;
